<template>
  <div class="app-container calendar-list-container">
    <div class="filter-container">
      <el-row>
        <el-col :span="6">
          <el-button class="filter-item" size="small" style="margin-left: 10px;" @click="handleCreate" type="primary" icon="el-icon-edit">添加</el-button>
          <el-button class="filter-item" size="small" style="margin-left: 10px;" @click="handleDelete" type="primary" icon="el-icon-edit">删除</el-button>
        </el-col>
        <el-col :span="18" style="text-align: right">
          <el-input v-model="listQuery.condition.name" @keyup.enter.native="handleFilter" size="small" style="width: 200px" class="filter-item fsc-search" placeholder="角色名称">
          </el-input>
          <el-button class="filter-item" size="small" type="primary" v-waves icon="el-icon-search" @click="handleFilter">搜索</el-button>
          <!--<el-button class="filter-item" size="small" type="primary" v-waves icon="el-icon-circle-plus-outline" @click="moreCondition">更多</el-button>-->
          <!--<el-button class="filter-item" size="small" type="primary" v-waves icon="el-icon-search" @click="changeCol">选择列</el-button>-->
          <el-dropdown trigger="click" :hide-on-click=false style="float: right;margin-left: 10px">
            <span class="el-dropdown-link">
              <el-button class="filter-item" size="small" type="primary" v-waves>
                选择列<i class="el-icon-arrow-down el-icon--right"></i>
              </el-button>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item>
                <el-checkbox-group v-model="checkboxVal">
                  <el-checkbox label="id">角色id</el-checkbox>
                  <el-checkbox label="name">角色名称</el-checkbox>
                  <el-checkbox label="title">角色标题</el-checkbox>
                  <el-checkbox label="description">描述</el-checkbox>
                </el-checkbox-group>
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </el-col>
      </el-row>
      <div style="clean:both"></div>
    </div>

    <!--<div :class="{'search-transition':searchFlag,h0:true,h70:searchFlag}">-->
      <!--<p>fdsjfklsdfjlsdsjdlfj</p>-->
    <!--</div>-->

    <div style="clean:both"></div>

    <el-table :key='tableKey' ref="multipleTable" :data="list" v-loading="listLoading"
              element-loading-text="给我一点时间" border fit highlight-current-row
              style="width: 100%;margin-top:5px" @selection-change="handleSelectionChange">
      <el-table-column type="selection"></el-table-column>
      <el-table-column align="center" label="序号">
        <template slot-scope="scope">
          <span>{{scope.$index+1}}</span>
        </template>
      </el-table-column>
      <el-table-column :key='key' v-for='(value,key) in formThead' :label="value.title">
        <template slot-scope="scope">
          {{scope.row[value.key]}}
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="220" class-name="small-padding">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="handleAuthorize(scope.row.id)">授权</el-button>
        </template>
      </el-table-column>

    </el-table>

    <div v-show="!listLoading" class="pagination-container">
      <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page.sync="listQuery.current"
                     :page-sizes="[10,20,30, 50]" :page-size="listQuery.size" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form :rules="rules" ref="dataForm" :model="temp" label-position="left" label-width="100px" style='width: 400px; margin-left:50px;'>
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="temp.name" placeholder="请输入角色名称"></el-input>
        </el-form-item>
        <el-form-item label="角色标题" prop="title">
          <el-input v-model="temp.title"></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="temp.description"></el-input>
        </el-form-item>
        <!--<el-form-item label="排序" prop="orders">-->
          <!--<el-input v-model="temp.orders"></el-input>-->
        <!--</el-form-item>-->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="createData">确 定</el-button>
        <el-button v-else type="primary" @click="updateData">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="角色授权" :visible.sync="dialogTreeVisible" :before-close="handleClose">
      <el-input placeholder="输入关键字进行过滤"
        v-model="filterText">
      </el-input>
      <el-tree :data="treeData" show-checkbox default-expand-all :filter-node-method="filterNode"
               node-key="id" ref="tree" highlight-current :props="defaultProps" style="height: 400px;overflow-y:scroll" class="mt5">
      </el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogTreeVisible = false">取 消</el-button>
        <el-button type="primary" @click="updateAuthorize">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>
<script>
  import { queryPage, create, update, deleted, treeAllPermisson, listOwnBottomPermisson, updateRoleAuthorize } from '@/api/sysrole'
  import waves from '@/directive/waves' // 水波纹指令
  //  import { parseTime } from '@/utils'
  const defaultFormThead = [
    { key: 'id', title: '角色id', width: '' },
    { key: 'name', title: '角色名称', width: '' },
    { key: 'title', title: '角色标题', width: '' },
    { key: 'description', title: '描述', width: '' }] // 默认选中项
  export default {
    name: 'role',
    directives: {
      waves
    },
    data() {
      return {
        key: 1, // table key
        checkboxVal: ['id', 'name', 'title', 'description'], // checkboxVal
        formThead: defaultFormThead, // 默认表头
        desc: true,
        tableKey: 0,
        searchFlag: true,
        list: null,
        multipleSelection: [],
        listLoading: true,
        total: null,
        listQuery: {
          current: 1,
          size: 10,
          order: '',
          condition: {
            name: undefined
          }
        },
        temp: {
          id: undefined,
          name: '',
          title: '',
          description: '',
          orders: undefined
        },
        dialogFormVisible: false,
        dialogStatus: '',
        textMap: {
          update: '编辑',
          create: '创建'
        },
        rules: {
          name: [{ required: true, message: '角色名称不能为空', trigger: 'change' }],
          title: [{ required: true, message: '角色标题不能为空', trigger: 'change' }],
          orders: [{ required: true, message: '排序不能为空', trigger: 'change' }]
        },
        dialogTreeVisible: false,
        filterText: '',
        treeData: [],
        defaultProps: {
          children: 'children',
          label: 'label'
        },
        roleId: undefined
      }
    },
    created() {
      this.getList()
      this.buildPermissionTree()
    },
    watch: {
      filterText(val) {
        this.$refs.tree.filter(val)
      },
      checkboxVal(valArr) {
        console.log('当前的状态：', valArr)
        this.formThead = defaultFormThead.filter(v => {
          for (let i = 0; i < valArr.length; i++) {
            if (v.key === valArr[i]) {
              return v
            }
          }
        })
      }
    },
    methods: {
      changeCol() {
        this.desc = !this.desc
        console.log('当前转台', this.desc)
      },
      getList() {
        this.listLoading = true
        queryPage(this.listQuery).then(response => {
          this.list = response.data.records
          this.total = response.data.total
          this.listLoading = false
        })
      },
      handleFilter() {
        this.listQuery.current = 1
        this.getList()
      },
      handleSizeChange(val) {
        this.listQuery.size = val
        this.getList()
      },
      handleCurrentChange(val) {
        this.listQuery.current = val
        this.getList()
      },
      resetTemp() {
        this.temp = {
          id: undefined,
          name: '',
          title: '',
          description: '',
          orders: undefined
        }
      },
      handleCreate() {
        this.resetTemp()
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      createData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            // this.temp.id = parseInt(Math.random() * 100) + 1024 // mock a id
//            this.temp. = '原创作者'
            create(this.temp).then(response => {
              this.temp = response.data
              this.list.unshift(this.temp)
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '创建成功',
                type: 'success',
                duration: 2000
              })
            })
          }
        })
      },
      handleUpdate(row) {
        this.temp = Object.assign({}, row) // copy obj
        this.temp.timestamp = new Date(this.temp.timestamp)
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      updateData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            const tempData = Object.assign({}, this.temp)
            tempData.timestamp = +new Date(tempData.timestamp) // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464
            update(tempData).then(() => {
              for (const v of this.list) {
                if (v.id === this.temp.id) {
                  const index = this.list.indexOf(v)
                  this.list.splice(index, 1, this.temp)
                  break
                }
              }
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '更新成功',
                type: 'success',
                duration: 2000
              })
            })
          }
        })
      },
      handleDelete() {
        var ids = []
        this.multipleSelection.forEach(function(item, index, array) {
          ids.push(item.id)
        })
        deleted(ids).then(response => {
          if (response.code === 0) {
            for (var i = 0; i < ids.length; i++) {
              this.removeList(ids[i])
            }
            this.$notify({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
          } else {
            this.$notify({
              title: '失败',
              message: response.message,
              type: 'fail',
              duration: 2000
            })
          }
        })
      },
      removeList(id) {
        const index = this.list.findIndex(d => d.id === id)
        this.list.splice(index, 1)
      },
      handleSelectionChange(val) {
        this.multipleSelection = val
      },
      filterNode(value, data) {
        if (!value) return true
        return data.label.indexOf(value) !== -1
      },
      buildPermissionTree() {
        treeAllPermisson().then(response => {
          this.treeData = response.data
        })
      },
      handleAuthorize(roleId) {
        this.roleId = roleId
        listOwnBottomPermisson(roleId).then(response => {
          if (response.data != null) {
            this.$refs.tree.setCheckedKeys(response.data)
          } else {
            this.$refs.tree.setCheckedKeys([])
          }
        })
        this.dialogTreeVisible = true
      },
      updateAuthorize() {
        const permIds = this.$refs.tree.getCheckedKeys(false)
        updateRoleAuthorize(this.roleId, permIds).then(response => {
          if (response.code === 0) {
            this.$notify({
              title: '成功',
              message: '授权成功',
              type: 'success',
              duration: 2000
            })
            this.$refs.tree.setCheckedKeys([])
            this.dialogTreeVisible = false
          } else {
            this.$notify({
              title: '失败',
              message: response.message,
              type: 'fail',
              duration: 2000
            })
          }
        })
      },
      handleClose(done) {
        this.$refs.tree.setCheckedKeys([])
        done()
      },
      moreCondition() {
        this.searchFlag = !this.searchFlag
        console.log('让他显示,当前状态', this.searchFlag)
      }
    }
  }
</script>

<style type="text/scss" lang="scss" scoped>
  .el-collapse-item__header{
    display: none;
  }
</style>
